package android.demo.engine;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.demo.R;
import android.os.Bundle;
import android.widget.Toast;

/**
 * @author  carlo
 */
public class RootActivity extends Activity{

	
	/**
	 * @uml.property  name="process"
	 * @uml.associationEnd  
	 */
	private BusinessProcess process;
	private List<ActivityListener> listeners;
	
	/* (non-Javadoc)
	 * @see android.demo.engine.TaskVisitor#visit(android.demo.engine.ActivityTask)
	 */

	@Override
	protected void onActivityResult(int taskId, int resultCode, Intent data) {
		super.onActivityResult(taskId, resultCode, data);
		switch (resultCode) {
		case RESULT_OK: //task ended, handle result and go to the next
			notifyActivityResult(taskId,data);
			break;
		case RESULT_CANCELED:
			notifyBackRequest(taskId);
			break;
		default:
			break;
		}
	}

	private void notifyBackRequest(int taskId) {
		for(ActivityListener listener : listeners)
			listener.onBackRequest(taskId);
	}

	private void notifyActivityResult(int taskId, Intent data) {
		for(ActivityListener listener : listeners)
			listener.onActivityResult(taskId,data);
	}

	/**
	 * Methods used to handle activity's lifecycle
	 */
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.listeners= new ArrayList<ActivityListener>();
		process =new BusinessProcess(savedInstanceState,this);
		process.exec();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		process.saveState(outState);
	}
	
	public void addListener(ActivityListener listener){
		listeners.add(listener);
	}
	
	/**
	 * book loan/return process
	 * 
	 * start ->(A) choose a book ->(S) make a loan ->(A) return a book -> stop
	 * 
	 */
	public void showToast(CharSequence text) {
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(this, text, duration);
		toast.show();
	}
}
